package com.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * 客户端实际业务处理
 */
public class TimeClientHandler extends ChannelHandlerAdapter implements ChannelHandler {
    private final ByteBuf firstMessage;

    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();

        this.firstMessage = Unpooled.buffer(req.length);
        this.firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
//        Scanner sc = new Scanner(System.in);
//        System.out.println("please input!");
//        String s = sc.nextLine();//接受键盘字符串
//        while (!s.equals("exit")) {
//            byte[] req = s.getBytes();
//            this.firstMessage = Unpooled.buffer(req.length);
//            this.firstMessage.writeBytes(req);
            ctx.writeAndFlush(firstMessage);
//            s = sc.nextLine();
//        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        super.channelRead(ctx, msg);
        ByteBuf buf = (ByteBuf) msg;
        byte[] resp = new byte[buf.readableBytes()];
        buf.readBytes(resp);


        String boby = new String(resp, "UTF-8");
        System.out.println("上线时间：" + boby);


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
